package io.linfeng.modules.app.utils.redismq;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.linfeng.common.enums.CommentStatus;
import io.linfeng.common.utils.*;
import io.linfeng.modules.admin.entity.CommentEntity;
import io.linfeng.modules.admin.entity.PostEntity;
import io.linfeng.modules.admin.service.CommentService;
import io.linfeng.modules.admin.service.MessageService;
import io.linfeng.modules.admin.service.PostService;
import io.linfeng.modules.admin.service.SensitiveService;
import io.linfeng.modules.sys.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 消息订阅者
 * @author linfeng
 * @date 2024/7/17 17:07
 */
@Slf4j
@Component
public class MessageSubscriber implements MessageListener {

    @Autowired
    private SensitiveService sensitiveService;
    @Autowired
    private PostService postService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private RedisUtils redisUtils;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String receivedMessage = message.toString();
        // 处理接收到的消息
        log.info("Received message:{}",receivedMessage);
        String[] split = receivedMessage.split(":");
        switch (split[0]) {
            case Constant.POST_CONTENT_CHECK:
                if(NumberUtil.isInteger(split[1])){
                    handlePostCheck(Integer.valueOf(split[1]));
                }
                break;
            case Constant.COMMENT_CONTENT_CHECK:
                if(NumberUtil.isInteger(split[1])){
                    handCommentImgCheck(Integer.valueOf(split[1]));
                }
                break;
            case Constant.POST_READ_NUM:
                if(NumberUtil.isInteger(split[1])){
                    handPostPv(Integer.valueOf(split[1]));
                }
                break;

        }
    }

    /**
     * 审核帖子图片视频内容
     * @param postId
     */
    private void handlePostCheck(Integer postId){
        PostEntity post = postService.getById(postId);
        if(post!=null && post.getStatus().equals(Constant.POST_REVIEWED)){
            List<String> list = JsonUtils.JsonToList(post.getMedia());
            if(post.getType().equals(Constant.POST_TYPE_VIDEO)){
                boolean result = sensitiveService.checkVideo(list.get(0));
                if(!result){
                    //审核未通过，下架帖子
                    post.setStatus(Constant.POST_BANNER);
                    postService.updateById(post);
                    String content = StrUtil.format(Constant.AI_DOWN, post.getTitle());
                    messageService.sendMessageNotAsync(0, post.getUid(), post.getId(), Constant.PUSHARTICLE, content, Constant.TITLE_VIOLATION);
                }else{
                    post.setStatus(Constant.POST_NORMAL);
                    postService.updateById(post);
                }
            }else if(post.getType().equals(Constant.POST_TYPE_TEXT)){
                boolean tmp=true;
                for (int i = 0; i < list.size(); i++) {
                    boolean result = sensitiveService.checkImg(list.get(i));
                    if(!result){
                        //审核未通过，下架帖子
                        post.setStatus(Constant.POST_BANNER);
                        postService.updateById(post);
                        tmp=false;
                        String content = StrUtil.format(Constant.AI_DOWN, post.getTitle());
                        messageService.sendMessageNotAsync(0, post.getUid(), post.getId(), Constant.PUSHARTICLE, content, Constant.TITLE_VIOLATION);
                        break;
                    }
                }
                if(tmp){
                    post.setStatus(Constant.POST_NORMAL);
                    postService.updateById(post);
                }
            }
        }
    }

    /**
     * 审核评论的图片
     * @param commentId
     */
    private void handCommentImgCheck(Integer commentId){
        CommentEntity comment = commentService.getById(commentId);
        if(comment!=null && !WechatUtil.isEmpty(comment.getImg())){
            boolean result = sensitiveService.checkImg(comment.getImg());
            if(!result){
                comment.setStatus(CommentStatus.OFF.getValue());
                commentService.updateById(comment);
                String content = StrUtil.format(Constant.AI_COMMENT_DOWN, comment.getContent());
                messageService.sendMessageNotAsync(0, comment.getUid().intValue(), comment.getPostId().intValue(), Constant.PUSHARTICLE, content, Constant.TITLE_VIOLATION);
                //清理评论列表缓存
                redisUtils.delete(ConfigConstant.COMMENT_KEY+comment.getPostId());
                //如果评论发布策略为直接过审，那么需要修改评论数量缓存
                if(configService.getValue(Constant.COMMENT_CHECK).equals("0")){
                    List<CommentEntity> child = commentService.lambdaQuery().eq(CommentEntity::getPid, comment.getId()).list();
                    redisUtils.hashChange(RedisKeys.getPostKey(comment.getPostId().intValue()),ConfigConstant.POST_COMMENT_NUM,-(child.size()+1));
                }
            }
        }
    }

    /**
     * 帖子浏览量添加
     * @param postId
     */
    private void handPostPv(Integer postId){
        UpdateWrapper<PostEntity> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",postId);
        wrapper.setSql("`read_count` = `read_count` + 1");
        postService.update(wrapper);
    }

}
